import './App.scss'

// 导入子组件
import { CartHeader } from './components/CartHeader'
import { CartFooter } from './components/CartFooter'
import { GoodsItem } from './components/GoodsItem'
import { useState, useEffect } from 'react'
import axios from 'axios'

const http = axios.create({
  baseURL: 'http://localhost:8888',
})

export default function App() {
  // 商品列表数据
  const [goodsList, setGoodsList] = useState([])
  // 全选状态
  const [checkAll, setCheckAll] = useState(false)

  // 请求商品列表数据
  const getGoodsList = async () => {
    const res = await http.get('/goodsList')

    setGoodsList(res.data)
    // console.log(res,111)
  }

  // 辅助hooks
  useEffect(() => {
    getGoodsList()
  }, [])

  // 切换单个商品选中状态
  const checkedChange = (id, check) => {
    console.log(id, check)
    const newList = goodsList.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          goods_state: check,
        }
      }
      return item
    })
    // 更新本地数据
    setGoodsList(newList)

    // 发送数据更新状态
    http.patch(`/goodsList/${id}`, {
      goods_state: check,
    })

    setCheckAll(newList.every((item) => item.goods_state))
  }

  // 控制全选状态
  const checkAllChange = (checkAll) => {
    // console.log(checkAll)

    setCheckAll(checkAll)

    // 修改本地状态
    setGoodsList(
      goodsList.map((item) => {
        return {
          ...item,
          goods_state: checkAll,
        }
      })
    )

    // 发送请求修改数据
    goodsList.forEach((item) => {
      http.patch(`/goodsList/${item.id}`, {
        goods_state: checkAll,
      })
    })
  }

  // 总数量
  const allCount = goodsList.reduce((prevCount, item) => {
    if (item.goods_state) {
      return prevCount + item.goods_count
    } else {
      return prevCount
    }
  }, 0)

  // 总金额
  const allPrice = goodsList.reduce((prevPrice, item) => {
    if (item.goods_state) {
      return prevPrice + item.goods_count * item.goods_price
    } else {
      return prevPrice
    }
  }, 0)

  return (
    <div className="app">
      {/* 标题 */}
      <CartHeader>购物车案例</CartHeader>

      {/* 商品列表项 */}
      {goodsList.map((item) => {
        return (
          <GoodsItem key={item.id} {...item} checkedChange={checkedChange} />
        )
      })}

      {/* 底部 */}
      <CartFooter
        checkAll={checkAll}
        checkAllChange={checkAllChange}
        allCount={allCount}
        allPrice={allPrice}
      />
    </div>
  )
}
